package database;

import entity.Account;
import manager.AccountManager;
import java.sql.CallableStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Noi
 */
public class AccountManagerDB {

    private CallableStatement cstmt;
    private Statement stmt;
    private java.sql.Connection conn;
    private ResultSet rs;

    public AccountManagerDB(java.sql.Connection conn) {
        this.conn = conn;
    }
    
    public void loadData(AccountManager accountManager) {
        try {
            stmt = conn.createStatement();
            cstmt = conn.prepareCall("{call sp_GetAccount}");
            rs =  cstmt.executeQuery();
            while(rs.next()) {
                String accountID = rs.getString("AccountID");
                String password = rs.getString("Password");
                int authorization = rs.getInt("Authorization");
                boolean status = rs.getBoolean("Status");
                Account account = new Account(accountID, password, authorization, status);
                accountManager.add(account);
            }
            rs.close();
            cstmt.close();
        } catch (SQLException ex) {
            Logger.getLogger(AccountManagerDB.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    public void deleteAccount(Account obj) {
        try {
            cstmt = conn.prepareCall("{call sp_DeleteAccount(?)}");
            cstmt.setString(1, obj.getAccountID());
            cstmt.executeUpdate();
            cstmt.close();
        } catch (SQLException ex) {
            Logger.getLogger(AccountManagerDB.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    public void insertAccount(Account obj) {
        try {
            cstmt = conn.prepareCall("{call sp_InsertAccount(?,?,?)}");
            cstmt.setString(1, obj.getAccountID());
            cstmt.setString(2, obj.getPassword());
            cstmt.setInt(3, obj.getAuthorization());
            cstmt.executeUpdate();
            cstmt.close();
        } catch (SQLException ex) {
            Logger.getLogger(AccountManagerDB.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    public void updateAccount(Account obj) {
        try {
            cstmt = conn.prepareCall("{call sp_UpdateAccount(?,?,?,?)}");
            cstmt.setString(1, obj.getAccountID());
            cstmt.setString(2, obj.getPassword());
            cstmt.setInt(3, obj.getAuthorization());
            cstmt.setBoolean(4, obj.isStatus());
            cstmt.executeUpdate();
            cstmt.close();
        } catch (SQLException ex) {
            Logger.getLogger(AccountManagerDB.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
